<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\LinkSaveRequest;
use App\Http\Requests\LinkUpdateRequest;
use App\Models\Link;
use App\Http\Responses\Response;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LinkController extends Controller
{
    /**
     * 查询所有链接(后台)
     * @return JsonResponse
     */
    public function list_all()
    {
        $links = Link::orderBy("link_weight", "desc")->get();
        return Response::resource_success($links);
    }


    /**
     * 修改名称和url
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * @throws ValidationException
     */
    public function update(LinkUpdateRequest $request, $id)
    {
        $result = [
            "code" => 200,
            "message" => "ok"
        ];
        $cleanData = $request->validated();


        $link = Link::find($id);
        if (is_null($link)) {
            return Response::update_error();
        }
        if (isset($cleanData["name"])) {
            $link->link_name = $cleanData["name"];
        }
        if (isset($cleanData["url"])) {
            $link->link_url = $cleanData["url"];
        }
        if (isset($cleanData["weight"])) {
            $link->link_weight = $cleanData["weight"];
        }
        if (isset($cleanData["status"])) {
            $link->link_status = $cleanData["status"];
        }
        try {
            $link->save();
        } catch (Exception $exception) {
            return Response::update_error();
        }

        return Response::update_success($link);
    }


    public function delete($id)
    {
        $link = Link::find($id);
        Link::destroy($id);
        if (Link::find($id)) {
            return Response::delete_error();
        }
        return Response::delete_success($link);
    }

    public function save(LinkSaveRequest $request)
    {

        $cleanData = $request->validated();

        $link = Link::create([
            "link_name" => $cleanData["name"],
            "link_url" => $cleanData["url"],
            "link_weight" => 0,
            "link_status" => 0,
            "link_create_time" => date("Y-m-d H:i:s")
        ]);

        try{
            $link->save();
        } catch (Exception $exception){
            return Response::insert_error();
        }

        return Response::insert_success($link);
    }
}
